package me.mayt.wxfl.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;


import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by mayt on 2018/8/24.
 */
@RestController
@RequestMapping(value = "/token/check")
public class TokenController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenController.class);

    public String check(String requestBody, HttpServletRequest request) {
		LOGGER.info("request.getParameterMap() = {}", JSON.toJSONString(request.getParameterMap()));
		LOGGER.info("requestBody = {}", requestBody);
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        LOGGER.info("{}, {}, {}, {}", signature, timestamp, nonce, echostr);
        String token = "123456";

        List<String> list = new ArrayList<>();
        list.add((token));
        list.add(timestamp);
        list.add(nonce);
        Collections.sort(list);
        
        return echostr;
    }
    
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(value = "signature", required = false) String signature,
                          @RequestParam(value = "timestamp", required = false) String timestamp,
                          @RequestParam(value = "nonce", required = false) String nonce,
                          @RequestParam(value = "echostr", required = false) String echostr) {
      LOGGER.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

      if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
        throw new IllegalArgumentException("请求参数非法，请核实!");
      }

//      if (this.wxService.checkSignature(timestamp, nonce, signature)) {
//        return echostr;
//      }

      return "非法请求";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody, @RequestParam("signature") String signature,
                       @RequestParam(value = "encrypt_type", required = false) String encType,
                       @RequestParam(value = "msg_signature", required = false) String msgSignature,
                       @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
      LOGGER.info("\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
          + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
        signature, encType, msgSignature, timestamp, nonce, requestBody);

//      if (!this.wxService.checkSignature(timestamp, nonce, signature)) {
//        throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
//      }

//      String out = null;
//      if (encType == null) {
//        // 明文传输的消息
//        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
//        WxMpXmlOutMessage outMessage = this.wxService.route(inMessage);
//        if (outMessage == null) {
//          return "";
//        }
//
//        out = outMessage.toXml();
//      } else if ("aes".equals(encType)) {
//        // aes加密的消息
//        WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
//          this.wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
//        this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
//        WxMpXmlOutMessage outMessage = this.wxService.route(inMessage);
//        if (outMessage == null) {
//          return "";
//        }
//
//        out = outMessage.toEncryptedXml(this.wxService.getWxMpConfigStorage());
//      }
//
//      this.logger.debug("\n组装回复信息：{}", out);

      return "";
    }
}
